import type { Record as PrismaRecord } from '@fill/client';
import { fs } from '@tauri-apps/api';
import { exists } from '@tauri-apps/api/fs';
import { basename, join } from '@tauri-apps/api/path';
import { FILL_TABLE_COLLECTION, TABLE_COLLECTION } from '../../constants/default';
import type { IUploadFile } from '../../util';
import { appPath, filesPath, resourcePath } from '../../util';
import type { OtherFile } from '../types/other_file';
import type { w_sp_history } from '../types/sp_history';
import type { ILanhaiDataSchema, ILanhaiSpDef, ILanhaiSpNode, IPipe } from './interface';
import { Pipe } from './pipe';

export class Record extends Pipe implements IPipe {
  async import(data: ILanhaiDataSchema, _sp_def: ILanhaiSpDef, _sp_node: ILanhaiSpNode) {
    if (!data.has(TABLE_COLLECTION.SP_HISTORY))
      return [];

    const _data = data.get(TABLE_COLLECTION.SP_HISTORY)?.data as w_sp_history[];

    const results = await Promise.all(
      _data.map(async (item): Promise<PrismaRecord> => {
        const attachment: IUploadFile[] = (
          await Promise.all(
            JSON.parse(item.F_SMCL_ ? item.F_SMCL_ : '[]').map(async (_item: OtherFile) => {
              try {
                const ext = (await basename(_item.fileName)).split('.')[1];
                const file_name = `${_item.fileId}.${ext}`;
                const path = await join(this.importPath, file_name);

                if (!await exists(path)) {
                  console.log(`文件 - ${path} - 不存在`);
                  return null;
                }

                const target = await join(await filesPath(), file_name);
                await fs.copyFile(path, target);

                const url = target.replace(await appPath(), target);
                return ({
                  uid: _item.fileId, // 文件id
                  name: _item.fileName, // 原名
                  fileName: file_name, // 文件名
                  base: url, // 相对路径
                  size: 0,
                  ext,
                  url: await resourcePath(url), // 资源全路径
                } as IUploadFile);
              }
              catch (error) {
                return null;
              }
            }),
          )
        ).filter(item => !!item);

        item.F_SMCL_ = JSON.stringify(attachment);

        // 不存储 uuid
        // 导入时清空相关 relation_uuid 的记录 重新插入
        return {
          uuid: item.ID_,
          relation_uuid: item.F_RELID_,
          content: JSON.stringify(item),
          module: item.F_TYPE_,
          created_at: item.CREATE_TIME_,
          updated_at: item.UPDATE_TIME_,
          approval_at: item?.F_SPSJ_ || '',
          sended_at: item.F_FSSJ_,
        };
      }),
    );

    return Promise.resolve([{
      module: FILL_TABLE_COLLECTION.RECORD,
      main: false,
      text: [],
      data: results,
    }]);
  }

  async export() {
    return {};
  }
}
